package net.yla.smartbus.core.util;

import com.vip.vjtools.vjkit.time.DateUtil;
import io.swagger.models.auth.In;
import jodd.util.StringUtil;
import net.yla.smartbus.module.ba.dept.mapper.DeptMapper;
import net.yla.smartbus.module.ba.duty.mapper.DutyMapper;
import net.yla.smartbus.module.ba.employee.entity.EmployeeEntity;
import net.yla.smartbus.module.ba.group.entity.GroupEntity;
import net.yla.smartbus.module.ba.group.mapper.GroupMapper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *@author:LiuJie
 *@date:2021/6/11
 *@description:excel文件导入
 */
@Component
public class UploadExcelData {
    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private DutyMapper dutyMapper;

    /**
     * 行数
     */
    private int totalRows = 0;
    /**
     * 列数
     */
    private int totalCells = 0;

    /**
     * 错误提示信息
     */

    private String errorMsg;


    public UploadExcelData() {

    }

    public int getTotalRows() {
        return totalRows;
    }

    public void setTotalRows(int totalRows) {
        this.totalRows = totalRows;
    }

    public int getTotalCells() {
        return totalCells;
    }

    public void setTotalCells(int totalCells) {
        this.totalCells = totalCells;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public Date finaStringDateToDate(String value) {
        Date date = null;
        boolean status = value.contains("/");
        if (!value.equals("")) {
            if (value.length() == 5 || !status) {
                Calendar calendar = new GregorianCalendar(1900, 0, -1);
                Date da = calendar.getTime();
                date = DateUtil.addDays(da, Integer.parseInt(value.trim()));
            } else if (value.length() == 8 || status) {
                DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                try {
                    date = df.parse(value);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return date;
    }









    public Date stringDateParseDate(String datevalue) {
        Date value = null;
        if (!datevalue.equals("")) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            try {
                value = df.parse(datevalue);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

    public Integer stringToInteger(String value) {
        Integer integerValue = null;
        if (!value.equals("")) {
            integerValue = Integer.valueOf(value);
        }
        return integerValue;
    }

    /**
     * 读取人员信息
     * @param file
     * @return
     */
    public List<EmployeeEntity> readPersonExcel(MultipartFile file) {
        List<EmployeeEntity> list = null;
        Workbook wb = null;
        if (file!=null) {
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                //创建Excel处理对象
                //String extString = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                wb = new XSSFWorkbook(inputStream);
                //获取第一页
                Sheet sheet = wb.getSheetAt(0);
                this.totalRows = sheet.getPhysicalNumberOfRows();
                //获取所有的列数,前提是行数大于1,获取所有的列只需要知道第一行的列数即可
                if (this.totalRows > 1 && sheet.getRow(0) != null) {
                    //获取所有的行数
                    this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
                }//if
                //新建一个集合
                list = new ArrayList<>();
                //新建一个站点form
                EmployeeEntity form = null;
                for (int i = 1; i < this.totalRows; i++) {
                    Row row = sheet.getRow(i);
                    if (row == null) {
                        continue;
                    }
                    form = new EmployeeEntity();
                    Cell cell = null;
                    for (int j = 0; j < this.totalCells; j++) {
                        //获取列
                        cell = row.getCell(j);
                        if (null != cell) {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                        }
                        //如果这一列为空就创建一列并赋值为空防止空指针异常
                        if (null == cell) {
                            Cell nullCell = row.createCell(j);
                            nullCell.setCellValue("");
                        }
                    }//第二轮循环
                    //添加信息
                    //非空判断
                    if (StringUtil.isNotBlank(row.getCell(0).getStringCellValue())) {
                        //机构Id
                        String groupName = row.getCell(0).getStringCellValue();
                        Integer groupId = groupMapper.getGroupId(groupName);
                        if (groupId != null){
                            form.setGroupId(groupId);
                        }

                        //部门Id
                        String deptName = row.getCell(1).getStringCellValue();
                        Integer deptId = deptMapper.getDeptId(deptName);
                        if (deptId != null){
                            form.setDeptId(groupId);
                        }
                        //职务Id
                        String dutyName = row.getCell(2).getStringCellValue();
                        Integer dutyId = dutyMapper.getdutyId(dutyName);
                        if (dutyId != null){
                            form.setDutieId(dutyId);
                        }
                        //人员类型
                        String person = row.getCell(3).getStringCellValue();
                        if (person.equals("常规人员")){
                            form.setEmplyeeType(1);
                        }else if (person.equals("驾驶员")){
                            form.setEmplyeeType(2);
                        }
                        //人员名称
                        form.setName(row.getCell(4).getStringCellValue());
                        //性别
                        String gender = row.getCell(5).getStringCellValue();
                        if (gender.equals("男")){
                            form.setGender(1);
                        }else if (gender.equals("女")){
                            form.setGender(2);
                        }
                        //员工工号
                        form.setCode(row.getCell(6).getStringCellValue());
                        //员工卡号
                        form.setCardNo(row.getCell(7).getStringCellValue());
                        //出生日期
                        try {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                            form.setDateOfBirth(format.parse(row.getCell(8).getStringCellValue()));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        //移动电话
                        form.setPhone(row.getCell(9).getStringCellValue());
                        //拼音
                        form.setPinyin(ChangeToPinyin.toUpperStringsFirstCharPinYin(form.getName()));
                        //缩写
                        form.setAbbr(ChangeToPinyin.toFirstPinYin(form.getName()));
                        list.add(form);
                    }
                }
            }catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }


}
